package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejbSessions.ManagerUtenteRemote;
import EJBPackage.Utente;
/**
 * Servlet implementation class InfoPersonali
 */
public class InfoPersonali extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InfoPersonali() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	private void gestisciRichiesta(HttpServletRequest request, HttpServletResponse response){
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Utente/InfoPersonali.jsp");
		String update;
		try{
			update = request.getParameter("update");
			if(update!=null){
				String nome, cognome, indirizzo, telefono;
				Hashtable<String,String> env = new Hashtable<String,String>();
				env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
				env.put(Context.PROVIDER_URL,"localhost:1099");
				InitialContext jndiContext = new InitialContext(env);
				Object ref = jndiContext.lookup("ManagerUtente/remote");
				ManagerUtenteRemote manager = (ManagerUtenteRemote)ref;
				
				int idUtente = (Integer)request.getSession().getAttribute("userid");
				
				nome = request.getParameter("nome");
				cognome = request.getParameter("cognome");
				telefono = request.getParameter("telefono");
				if(telefono == ""){
					telefono = "-";
				}
				indirizzo = request.getParameter("email");
				if(indirizzo == ""){
					indirizzo = "-";
				}
				manager.updateUtente(idUtente,nome, cognome, indirizzo, telefono);
				request.getSession().setAttribute("nome",nome);
				request.getSession().setAttribute("cognome",cognome);
				request.getSession().setAttribute("indirizzo",indirizzo);
				request.getSession().setAttribute("telefono",telefono);
				request.getSession().removeAttribute("update");
			}
			dispatcher.forward(request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
